from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from lib.database import Base


class Community(Base):
    __tablename__ = "community"

    id = Column(Integer, primary_key=True)
    name = Column(String(256), nullable=False, index=True, comment="小区名称")
    lian_jia_id = Column(String(32), nullable=False, comment="该小区在链家中的uri id")
    wiwj_id = Column(String(32), comment="该小区在我爱我家中的uri id")
    district = Column(String(128), comment="该小区所在的区/县")
    area = Column(String(128), comment="该小区所在的板块")
    house_count = Column(Integer, comment="该小区的房屋总数")
    fees = Column(String(64), comment="物业费")
    birthday = Column(String(32), comment="该小区的建成时间")
    traffic = Column(String(128), comment="该小区的交通(离最近的地铁站)")
    three_month_sell_count = Column(Integer, comment="90天内的成交量(链家)")
    wiwj_six_month_sell_count = Column(Integer, comment="近6个月内的成交量(我爱我家)")
    month_see = Column(Integer, comment="30天内的带看量")
    sell_count = Column(Integer, comment="正在出售数量")
    followed_num = Column(Integer, comment="关注数量")

    community_dyn_list = relationship("CommunityDyn", passive_deletes=True)

    def dict(self):
        """model 转 dic"""
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}


class CommunityDyn(Base):
    """小区的历史数据"""
    __tablename__ = "community_dyn"

    id = Column(Integer, primary_key=True)
    three_month_sell_count = Column(Integer, comment="90天内的成交量")
    month_see = Column(Integer, comment="30天内的带看量")
    sell_count = Column(Integer, comment="正在出售数量")
    followed_num = Column(Integer, comment="关注数量")

    community_id = Column(Integer, ForeignKey('community.id', ondelete='cascade'))
    created_at = Column(DateTime, comment="数据创建时间", default=datetime.utcnow)
